﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SystemX;
using System.Windows.Browser;
using SalePoints.Models;
using SystemX.Web;
namespace SalePoints
{
	public partial class App : Application
	{
		public App()
		{
			this.Startup += this.Application_Startup;
			this.UnhandledException += this.Application_UnhandledException;
			this.CheckAndDownloadUpdateCompleted += new CheckAndDownloadUpdateCompletedEventHandler(App_CheckAndDownloadUpdateCompleted);
			InitializeComponent();
		}

		void App_CheckAndDownloadUpdateCompleted(object sender, CheckAndDownloadUpdateCompletedEventArgs e)
		{
			if (e.UpdateAvailable)
			{
				MessageBox.Show("An update has been downloaded. " +
					"Restart the application to run the new version.");
			}
			else if (e.Error != null && e.Error is PlatformNotSupportedException)
			{
				MessageBox.Show("An application update is available, " +
					"but it requires a new version of Silverlight. " +
					"Visit the application home page to upgrade.");
			}
		}

		private void Application_Startup(object sender, StartupEventArgs e)
		{
			if (e.InitParams != null)
			{
				foreach (var item in e.InitParams)
				{
					if (item.Key.ToLower() == "appsettings")
					{
						var dic = HttpUtility.UrlDecode(item.Value).DeserializeJSONStr1<Dictionary<string, string>>();
						this.Resources.Add(item.Key, dic);
					}
					else
					{
						this.Resources.Add(item.Key, item.Value);
					}
				}
			}
			this.RootVisual = new MainPage();
		}

		private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
		{
			// If the app is running outside of the debugger then report the exception using
			// a ChildWindow control.
			if (!System.Diagnostics.Debugger.IsAttached)
			{
				// NOTE: This will allow the application to continue running after an exception has been thrown
				// but not handled. 
				// For production applications this error handling should be replaced with something that will 
				// report the error to the website and stop the application.
				e.Handled = true;
				LogServices.AddLog(e.ExceptionObject,null);
			}
		}
	}
}